from datetime import datetime
from app.models.db_setup import db


class Order(db.Model):
    """订单模型"""

    __tablename__ = "Order"

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    order_number = db.Column(db.String(50), unique=True, nullable=False)
    user_id = db.Column(db.Integer, db.ForeignKey("User.id"), nullable=False)
    remarks = db.Column(db.Text)
    status = db.Column(
        db.String(20), default="pending"
    )  # pending, processing, completed, cancelled
    created_at = db.Column(db.DateTime, default=datetime.now)
    updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now)

    # 关联关系
    user = db.relationship("User", backref=db.backref("orders", lazy=True))
    order_items = db.relationship(
        "OrderItem", backref="order", lazy=True, cascade="all, delete-orphan"
    )

    def __init__(self, order_number, user_id, remarks=None):
        self.order_number = order_number
        self.user_id = user_id
        self.remarks = remarks
        self.status = "pending"

    def to_dict(self):
        """转换为字典"""
        return {
            "id": self.id,
            "orderNumber": self.order_number,
            "userId": self.user_id,
            "userName": self.user.username,
            "userOpenID": self.user.openid,
            "remarks": self.remarks,
            "status": self.status,
            "createdAt": self.created_at.isoformat() if self.created_at else None,
            "updatedAt": self.updated_at.isoformat() if self.updated_at else None,
            "items": [item.to_dict() for item in self.order_items],
        }


class OrderItem(db.Model):
    """订单项目模型"""

    __tablename__ = "OrderItem"

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    order_id = db.Column(db.Integer, db.ForeignKey("Order.id"), nullable=False)
    product_id = db.Column(db.Integer, db.ForeignKey("Product.id"), nullable=False)
    sku_code = db.Column(db.String(50))
    quantity = db.Column(db.Integer, default=1)
    price = db.Column(db.Float)
    created_at = db.Column(db.DateTime, default=datetime.now)

    # 关联关系
    product = db.relationship("Product", backref=db.backref("order_items", lazy=True))

    def __init__(self, order_id, product_id, sku_code=None, quantity=1, price=0):
        self.order_id = order_id
        self.product_id = product_id
        self.sku_code = sku_code
        self.quantity = quantity
        self.price = price

    def to_dict(self):
        """转换为字典"""
        return {
            "id": self.id,
            "orderId": self.order_id,
            "productId": self.product_id,
            "skuCode": self.sku_code,
            "quantity": self.quantity,
            "price": self.price,
            "createdAt": self.created_at.isoformat() if self.created_at else None,
            "product": self.product.to_dict() if self.product else None,
        }
